const winston = require("winston");
const db = require("./../server/db");
require("dotenv").config();

// 自定义 MySQL 日志传输
class MySQLTransport extends winston.Transport {
  constructor(options) {
    super(options);
  }

  async log(info, callback) {
    setImmediate(() => {
      this.emit("logged", info);
    });

    try {
      const connection = await db.getConnection();
      try {
        await connection.execute(
          "INSERT INTO logs (level, message, meta) VALUES (?, ?, ?)",
          [info.level, info.message, JSON.stringify(info.meta || {})]
        );
      } finally {
        connection.release();
      }
    } catch (error) {
      console.error("Error logging to MySQL:", error);
    }

    callback();
  }
}

// 创建 logger 实例
const logger = winston.createLogger({
  level: "info",
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    // 控制台输出
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      ),
    }),
    // MySQL 存储
    new MySQLTransport(),
  ],
});


module.exports = {
  logger
};
